<script setup lang="ts">
import { signup } from '@/api/login'
import router from '@/router'
import { computed, reactive } from 'vue'

const formValue = reactive({
  username: '',
  usernameMsg: computed(() => {
    if (formValue.username !== '' && formValue.username.length < 6) {
      return '账号的长度不能小于6位数'
    }
    return ''
  }),
  password: '',
  passwordMsg: computed(() => {
    if (formValue.password !== '' && formValue.password.length < 6) {
      return '密码的长度不能小于6位数'
    }
    return ''
  })
})
const signupSub = async () => {
  const res = await signup(formValue.username, formValue.password)
  if (res) {
    router.push('/login')
  }
}
</script>
<template>
  <div class="container d-flex justify-content-center align-items-center vh-100">
    <div class="col-12 col-sm-8 col-lg-6 col-xl-4 col-xxl-4">
      <form class="border shadow-sm rounded p-4">
        <legend class="d-flex justify-content-center">注册</legend>
        <div class="mb-4">
          <label for="exampleInputEmail1" class="form-label">用户名：</label>
          <input
            type="username"
            :class="['form-control', { 'is-invalid': formValue.usernameMsg }]"
            class="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            v-model="formValue.username"
          />
          <div class="invalid-feedback">
            {{ formValue.usernameMsg }}
          </div>
        </div>
        <div class="mb-5">
          <label for="exampleInputPassword1" class="form-label">密码：</label>
          <input
            type="password"
            class="form-control"
            :class="['form-control', { 'is-invalid': formValue.passwordMsg }]"
            id="exampleInputPassword1"
            v-model="formValue.password"
          />
          <div class="invalid-feedback">
            {{ formValue.passwordMsg }}
          </div>
        </div>
        <div class="d-flex flex-column align-items-center px-1">
          <button
            type="button"
            class="btn btn-primary w-100 mb-3 text-light"
            @click="signupSub()"
          >
            注册
          </button>
          <router-link
            to="/login"
            class="border rounded w-100 text-center text-decoration-none"
          >
            <button type="button" class="btn w-100">登录</button>
          </router-link>
        </div>
      </form>
    </div>
  </div>
</template>
<style></style>
